package com.ocean.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * https://leetcode.cn/problems/binary-tree-preorder-traversal/
 */
public class BinaryTreePreorderTraversal {
    public static void main(String[] args) {
        BinaryTreePreorderTraversal traversal = new BinaryTreePreorderTraversal();
        TreeNode root = TreeNode.getRoot();
        List<Integer> res = traversal.preorderTraversal2(root);
        System.out.println(res);
    }


    /**
     * 前序遍历：根->左->右
     *
     * @param root
     * @return
     */
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        preorder(root, res);
        return res;
    }

    public List<Integer> preorderTraversal2(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                res.add(root.getValue());
                stack.push(root);
                root = root.getLeft();
            }
            root = stack.pop();
            root = root.getRight();
        }
        return res;
    }


    public void preorder(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        res.add(root.getValue());
        preorder(root.getLeft(), res);
        preorder(root.getRight(), res);
    }
}
